package com.shop.user.mqHandler.config;


import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 'banxia'
 * @version 1.0
 * @description 用于交换机-消息队列的注册
 * @date 2023/2/28 14:00
 */
@Configuration
public class RabbitConfig {

    //注册交换机
    @Bean
    public DirectExchange ttlExchange(){
        return new DirectExchange("ttl.direct");
    }

    //注册死信消息队列（消息不会被立刻传输过去！）
    @Bean
    public Queue ttlQueue(){
        return QueueBuilder.durable("ttl.queue")
                .ttl(1000*60*5) //假设只有30秒（debug测试，后期改）
                .deadLetterExchange("order.direct")
                .deadLetterRoutingKey("orderCancel") //指定该消息队列要转发到死信交换机所需要的key
                .build();
    }

    //绑定交换机和消息队列
    @Bean
    public Binding orderExchangeQueue(){
        return BindingBuilder.bind(ttlQueue()).to(ttlExchange()).with("ttl");
    }


    //----------------------------------------------------------------
    //失败重试消息队列和交换机
    @Bean
    public DirectExchange errorExchange(){
        return new DirectExchange("error.direct");
    }
    @Bean
    public Queue errorQueue(){
        return new Queue("error.queue");
    }
    @Bean
    public Binding errorBinding(){
        return BindingBuilder.bind(errorQueue())
                .to(errorExchange())
                .with("error");
    }

    //让发送失败的发送的该交换机！
    @Bean
    public MessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate){
        return new RepublishMessageRecoverer(rabbitTemplate,"error.direct","error");
    }

}
